//日期控件
var startpick = {
    choose: function (dates) {
        format: '', endpick.min = dates
        endpick.start = dates
    }
};
var endpick = {
    choose: function (dates) {
        startpick.max = dates
    }
};

// 从数据库读取所有省份
function listAllProvinces() {
    getAllProvinces(function (data) {
        var provinces = data.data;
        $(provinces).each(
            function (index, element) {
                $("#provinceId").append(
                    "<option value='" + element.id + "'>"
                    + element.name + "</option>");
            })
    });
}

// 查询
$(function () {
    var $proId = $('#search-proId');
    var $cityId = $('#search-cityId');
    $proId.change(function () {
        $this = $(this);
        $cityId.html('<option value="">全部</option>');
        if ($this.val() === '') {
            return;
        }
        getCitiesByProvinceId($this.val(), function (data) {
            var cities = data.data;
            $(cities).each(function (index, element) {
                var op = $('<option></option>').text(element.name);
                op.val(element.id);
                $cityId.append(op);
            });
        })
    });
    getAllProvinces(function (data) {
        var provinces = data.data;
        $(provinces).each(function (index, element) {
            var op = $('<option></option>').text(element.name);
            op.val(element.id);
            $proId.append(op);
        })
    });

    // 根据城市获取行政区
    $("#cityId").click(
        function () {
            var cityId = $("#cityId").find("option:selected").val();
            getDistrictByCityId(cityId, function (data) {
                var cities = data.data;
                $("#districtId").empty();
                $("#districtId").append(
                    "<option value='----'>----</option>");
                $(cities).each(
                    function (index, element) {
                        $("#districtId").append(
                            "<option value='" + element.id + "'>"
                            + element.name + "</option>");
                    })
            })
        });

    // 根据省份获取城市
    $("#provinceId").click(
        function () {
            var provId = $("#provinceId").find("option:selected").val();
            getCitiesByProvinceId(provId, function (data) {
                var cities = data.data;
                $("#cityId").empty();
                $("#cityId").append("<option value='----'>----</option>");
                $("#districtId").empty();
                $("#districtId").append(
                    "<option value='----'>----</option>");
                $(cities).each(
                    function (index, element) {
                        $("#cityId").append(
                            "<option value='" + element.id + "'>"
                            + element.name + "</option>");
                    })
            })
        });

    // 添加维修厂弹窗操作
    $('#modify1').on('click', function (event) {
        clearForm();
        isDisableForm(false);
        $('#btn-ok').removeAttr('disabled');

        event.preventDefault();

        listAllProvinces();

        modalShow(addRepairShop, onCancle);

    });

//    // 查询维修厂模块框的弹出
//     $('#edit-workStation-modal').modal({
//     wrapClassName: '.customer-class',
//     width: '600',
//     footer: 1,
//     okText: '确定',
//     cancelText: '取消',
//     onOk:
//     });
});


//	 $('#edit-workStation-modal').modal({
//	 wrapClassName: '.customer-class',
//	 width: '600',
//	 footer: 1,
//	 okText: '确定',
//	 cancelText: '取消'
//	 });

// 调用分页
laypage({
    cont: 'J_PagesPanel',
    skip: true,
    pages: pages,
    curr: currentPage,
    jump: function (obj, first) {
        if (!first) {
            var locationUrl = location.href;
            if (locationUrl.indexOf("?") > 0) {
                if (locationUrl.indexOf('page') < 0) {
                    location.href = locationUrl + '&page=' + obj.curr;
                } else {
                    location.href = locationUrl.replace(/page=\d*/, 'page='
                        + obj.curr);
                }
            } else {
                location.href = locationUrl + '?page=' + obj.curr;
            }
        }
    }
});

function getAllProvinces(successCall, errorCall) {
    $.ajax({
        url: projectContext + 'provinces',
        type: 'GET',
        async: false,
        success: successCall,
        error: errorCall
    });
}

function getCitiesByProvinceId(provinceId, successCall, errorCall) {
    $.ajax({
        url: projectContext + 'cityByProvince',
        type: 'GET',
        async: false,
        data: {
            'provinceId': parseInt(provinceId)
        },
        success: successCall,
        error: errorCall
    });
}

function getDistrictByCityId(cityId, successCall, errorCall) {
    $.ajax({
        url: projectContext + 'districtByCity',
        type: 'GET',
        async: false,
        data: {
            'cityId': parseInt(cityId)
        },
        success: successCall,
        error: errorCall
    });
}


function modalShow(okFun, cancelFun) {

    $('#edit-modal').modal({
        wrapClassName: '.customer-class',
        width: '600',
        footer: 1,
        okText: '确定',
        cancelText: '取消',
        onOk: okFun,
        onCancel: cancelFun
    })

}

function showRepairShop(e) {
    updateRepairShop(e, true);
    $('#btn-ok').attr('disabled', 'disabled');
}

function updateRepairShop(e, readOnly) {
    $('#btn-ok').removeAttr('disabled');
    event.preventDefault();
    $.ajax({
        url: projectContext + 'repair/shop',
        type: 'GET',
        data: {
            'id': parseInt($(e).data('sid'))
        },
        success: function (data) {
            if (data.code === 200) {
                s = data.data;
                insertIntoForm(s, readOnly);
                modalShow(function () {
                    var shop = {
                        'shopId': parseInt(s.shopId),
                        'name': $('#name').val(),
                        'districtID': parseInt($('#districtId').val()),
                        'address': $('#address').val(),
                        'longitude': parseFloat($('#longitude').val()),
                        'latitude': parseFloat($('#latitude').val()),
                        'contact': $('#contact').val(),
                        'cellPhone': $('#cellPhone').val(),
                        'phoneNo': $('#phoneNo').val(),
                        'cooperationId': $('#cooperationId').val(),
                        'openTime': $('#hours1').val() + ':' + $('#minutes1').val(),
                        'closeTime': $('#hours2').val() + ':' + $('#minutes2').val(),
                        'qualification': $('#qualification').val(),
                        'shopType': parseInt($('#shopType').val()),
                        'isClosed': $('#isClosed').val(),
                        'cooperationStart': $('#cooperationStart').val(),
                        'cooperationEnd': $('#cooperationEnd').val(),
                        'level': 1,
                        'maxRepairCars': 0
                    };
                    $.ajax({
                        url: projectContext + 'repair/shop',
                        type: 'PUT',
                        data: shop,
                        success: function (result) {
                            if (result.code === 200) {
                                alert('更新成功');
                                location.reload(true);
                            } else {
                                alert('数据服务器发生错误')
                            }
                        },
                        error: function () {
                            alert('应用服务器发生错误')
                        }
                    })

                }, function () {
                    // console.log('取消')
                })
            } else {
                alert('发生错误')
            }
        },
        error: function () {
            alert('发生错误')
        }
    })
}


function addRepairShop() {
    console.log("执行添加维修厂操作")
    var repairShop = {
        'address': $("#address").val(),
        'cellPhone': $("#cellPhone").val(),
        'contact': $("#contact").val(),
        'cooperationEnd': $("#cooperationEnd").val(),
        'cooperationId': 1,
        'cooperationStart': $("#cooperationStart").val(),
        'districtID': $("#districtId").find("option:selected").val(),
        'isClosed': $("#isClosed").find("option:selected").val(),
        'latitude': $("#latitude").val(),
        'longitude': $("#longitude").val(),
//		'level':1,
        'maxRepairCars': 100,
        'name': $("#name").val(),
        'phoneNo': $("#phoneNo").val(),
        'qualification': $("#qualification").find("option:selected").val(),
        'shopType': $("#shopType").find("option:selected").val(),
        'provinceId': $("#provinceId").find("option:selected").val(),
        'cityId': $("#cityId").find("option:selected").val(),
        'districtId': $("#districtId").find("option:selected").val(),
        'openTime': $("#hours1").find("option:selected").val() + ":" + $("#minutes1").find("option:selected").val(),
        'closeTime': $("#hours2").find("option:selected").val() + ":" + $("#minutes2").find("option:selected").val()
//		'shopId':724
    };

    $.ajax({
        url: projectContext + 'addRepairShop',
        data: repairShop,
        type: 'POST',
        success: function (data) {
            if (data.code === 200) {
                alert("添加成功");
            } else {
                alert("添加失败");
            }
        },
        error: function () {
            alert("添加失败");
            console.log("执行失败")
        },
//          dataType:'json'
    })
}

function onCancle() {

}

function insertIntoForm(data, readOnly) {
    var $provinceId = $('#provinceId');
    var $cityId = $('#cityId');
    var $districtId = $("#districtId");

    listAllProvinces();
    $provinceId.val(data.proId);
    getCitiesByProvinceId(data.proId, function (cities) {
        var cs = cities.data;
        $cityId.empty();
        $(cs).each(function (index, element) {
            var op = $('<option></option>').text(element.name);
            op.val(element.id);
            $cityId.append(op);
        })
    });
    $cityId.val(data.cityId);

    getDistrictByCityId(data.cityId, function (districts) {
        var ds = districts.data;
        $districtId.empty();
        $(ds).each(function (index, element) {
            var op = $('<option></option>').text(element.name);
            op.val(element.id);
            $districtId.append(op);
        })
    });
    $districtId.val(data.districtID);

    $('#name').val(data.name);
    $('#address').val(data.address);
    $('#longitude').val(data.longitude);
    $('#latitude').val(data.latitude);
    $('#contact').val(data.contact);
    $('#cellPhone').val(data.cellPhone);
    $('#phoneNo').val(data.phoneNo);
    $('#cooperationId').val(data.cooperationId);
    $('#hours1').val(data.openTime.slice(0, 2));
    $('#minutes1').val(data.openTime.slice(3, 5));
    $('#hours2').val(data.closeTime.slice(0, 2));
    $('#minutes2').val(data.closeTime.slice(3, 5));
    $('#qualification').val(data.qualification);
    $('#shopType').val(data.shopType + '');
    $('#isClosed').val(data.isClosed);
    $('#cooperationStart').val(data.cooperationStart);
    $('#cooperationEnd').val(data.cooperationEnd);

    isDisableForm(readOnly);
}

function clearForm() {

    var $cityId = $('#cityId');
    var $districtId = $('#districtId');
    $cityId.empty();
    $districtId.empty();

    $('#provinceId').val('');
    $cityId.val('');
    $('#name').val('');
    $districtId.val('');
    $('#address').val('');
    $('#longitude').val('');
    $('#latitude').val('');
    $('#contact').val('');
    $('#phoneNo').val('');
    $('#cellPhone').val('');
    $('#cooperationId').val('0');
    $('#hours1').val('00');
    $('#minutes1').val('00');
    $('#hours2').val('00');
    $('#minutes2').val('00');
    $('#qualification').val('0');
    $('#shopType').val('0');
    $('#isClosed').val('N');
    $('#cooperationStart').val('');
    $('#cooperationEnd').val('');
}

function isDisableForm(readOnly) {
    $('#provinceId').attr('disabled', readOnly);
    $('#cityId').attr('disabled', readOnly);
    $('#name').attr('disabled', readOnly);
    $('#districtId').attr('disabled', readOnly);
    $('#address').attr('disabled', readOnly);
    $('#longitude').attr('disabled', readOnly);
    $('#latitude').attr('disabled', readOnly);
    $('#contact').attr('disabled', readOnly);
    $('#cellPhone').attr('disabled', readOnly);
    $('#phoneNo').attr('disabled', readOnly);
    $('#cooperationId').attr('disabled', readOnly);
    $('#hours1').attr('disabled', readOnly);
    $('#minutes1').attr('disabled', readOnly);
    $('#hours2').attr('disabled', readOnly);
    $('#minutes2').attr('disabled', readOnly);
    $('#qualification').attr('disabled', readOnly);
    $('#shopType').attr('disabled', readOnly);
    $('#isClosed').attr('disabled', readOnly);
    $('#cooperationStart').attr('disabled', readOnly);
    $('#cooperationEnd').attr('disabled', readOnly);
}